package node.func;

import grammar.Lexer;
import grammar.MyError;
import lexical.Key;
import midcode.MidCode;
import midcode.MidcodeGenerator;
import midcode.OPType;
import node.Node;
import node.block.Block;
import symbol.Function;
import symbol.SymbolTable;

import java.util.ArrayList;

public class MainFuncDef implements Node {
    private final Lexer lexer;
    private final SymbolTable table;
    private final Node father;
    private Block block;
    public ArrayList<Node> nodes = new ArrayList<>();

    public MainFuncDef(Lexer lexer, SymbolTable table, Node father) {
        this.lexer = lexer;
        this.table = table;
        this.father = father;
        parseMainFuncDef();
    }

    private void parseMainFuncDef() {
        table.addFunction(new Function(lexer.getWord(1), "int"));
        nodes.add(lexer.getCurWord()); // int
        nodes.add(lexer.getCurWord()); // main
        table.addParams = true;
        nodes.add(lexer.getCurWord()); // (
        if (lexer.isWordType(0, Key.RPARENT)) {
            nodes.add(lexer.getCurWord()); // )
        } else {
            lexer.addError(new MyError(lexer.getWord(-1).lineNum, 'j'));
        }
        block = new Block(lexer, table, this);
        nodes.add(block);
    }

    @Override
    public Node getFather() {
        return father;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        for (Node word : nodes) {
            sb.append(word.toString());
        }
        return sb.append("<MainFuncDef>\n").toString();
    }

    @Override
    public String genMidCode() {
        MidcodeGenerator mg = MidcodeGenerator.getInstance();
        mg.startFuncDef("main");
        mg.addMidcode(new MidCode(OPType.FUNC_DECL, null, null, "main"));
        block.genMidCode();
        mg.addMidcode(new MidCode(OPType.EXIT, null, null, null));
        table.setLocalValueOffset("main");
        return "";
    }
}

